<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <style>
        .customization_toolBar {
            border: none;
        }

        .customization_toolBar .toolBar {
            border: none;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            height: 20px;
            margin: 15px 0px 0px 0px;
        }

        .customization_toolBar .toolBar .left_tool_div {
            flex-basis: 70%;
            height: 100%;
            display: flex;
            flex-direction: row;
            align-items: center;
        }

        .left_tool_div > * + * {
            margin-left: 4%;
        }

        .customization_toolBar .toolBar .right_tool_div {
            flex-basis: 30%;
            height: 100%;
            display: flex;
            flex-direction: row;
            justify-content: flex-end;
            align-items: center
        }

        .right_tool_div > * + * {
            margin-left: 10px;
        }

        .text-show-btn {
            border: none;
            font-size: 14px;
            color: #666666;
        }

        .text-show-btn:hover {
            color: #666666;
        }

        .cell_info_text {
            text-align: left;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            white-space: nowrap !important;
            overflow: hidden !important;
            text-overflow: ellipsis !important;
        }

        .cell_info_div {
            margin: 10px 0 10px 15px
        }

        .layui-table-cell {
            text-align: center;
            height: auto !important;
            white-space: normal;
            overflow: visible;
            text-overflow: inherit;
            word-break: break-all;
        }

        #delayedReceiptPopup .layui-form {
            width: 80%;
            text-align: left;
            margin: 10px 10px 10px 10px
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" lay-filter="searchForm">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">订单编号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="tradingId" autocomplete="off" class="layui-input"
                                       placeholder="请输入订单编号">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">手机号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="phone" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">物流单号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="courierNumber" autocomplete="off" class="layui-input"
                                       placeholder="请输入详细的物流单号">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <fieldset class="customization_toolBar">
            <div class="toolBar">
                <div class="left_tool_div">
                    <div>
                        <button class="layui-btn layui-btn-primary layui-btn-sm data-add-btn text-show-btn"
                                onclick="stateSearch('IN_TRANSIT')">
                            运输中<label id="IN_TRANSIT" style="color:#1aa0ff;text-decoration: underline;">(0)</label>
                        </button>
                    </div>
                    <div>
                        <button class="layui-btn layui-btn-primary layui-btn-sm data-add-btn text-show-btn"
                                onclick="stateSearch('SIGN')">
                            已签收<label id="SIGN" style="color:#00ba00;text-decoration: underline;">(0)</label>
                        </button>
                    </div>
                    <div>
                        <button class="layui-btn layui-btn-primary layui-btn-sm data-add-btn text-show-btn"
                                onclick="stateSearch('FORTYEIGHT_HOUR_RECEIVING_DATA')">
                            48小时自动收货<label id="FORTYEIGHT_HOUR_RECEIVING_DATA"
                                           style="color:#fa0000;text-decoration: underline;">(0)</label>
                        </button>
                    </div>
                    <div>
                        <button class="layui-btn layui-btn-primary layui-btn-sm data-add-btn text-show-btn"
                                onclick="stateSearch('BUSINESS_COMPLETED')">
                            已完成<label id="BUSINESS_COMPLETED"
                                      style="color:#fa0000;text-decoration: underline;">(0)</label>
                        </button>
                    </div>
                    <div>
                        <form class="layui-form">
                            <input type="checkbox" lay-skin="primary" lay-filter="showAll"
                                   title="全部">
                        </form>
                    </div>
                </div>
                <div class="right_tool_div">
                    <div>
                        <button class="layui-btn layui-btn-sm layui-btn delayedReceipt single-select—btn">
                            延时收货
                        </button>
                    </div>
                </div>
            </div>
        </fieldset>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
        <script type="text/html" id="orderInfoTemp">
            <div class="cell_info_div">
                <div class="cell_info_text">{{d.goodsName}}</div>
                <div class="cell_info_text">订单编号:<label style="color:#299af9;cursor:pointer;text-decoration: underline;"
                                                        onclick="toOrderDetail('{{d.moduleId}}')">{{d.tradingId}}</label>
                </div>
            </div>
        </script>
        <script type="text/html" id="deliveryTimeTemp">
            <div class="cell_info_div">
                <div class="cell_info_text">J:{{d.tradingTime}}</div>
                <div class="cell_info_text">F:{{d.deliveryTime}}</div>
            </div>
        </script>
        <script type="text/html" id="addressTemp">
            <div class="cell_info_div">
                <div class="cell_info_text" style="font-size: 14px">{{d.consigneeName}} {{d.phone}}</div>
                <div class="cell_info_text">{{d.consigneeAddress}}</div>
            </div>
        </script>
        <script type="text/html" id="logisticsInfoTemp">
            <div class="cell_info_div">
                <div class="cell_info_text" style="font-size: 14px;" id="countdown_{{d.id}}">

                </div>
                <div class="cell_info_text">
                    <label style="cursor:pointer;" onclick="toLogisticsSpreadDetail('{{d.moduleId}}')">
                        {{# if(d.businessStatus == "0"){ }}
                        <span style="color: #43a8ff;text-decoration: underline;">
                            {{d.statusName}}
                        </span>
                        {{# } }}
                        {{# if(d.businessStatus == "1"){ }}
                        <span style="color: #17d248;text-decoration: underline;">
                            已完成
                        </span>
                        {{# } }}
                        <span style="color: #43a8ff;text-decoration: underline;">| {{d.expressCompanyName}} {{d.courierNumber}}</span>
                    </label>
                </div>
            </div>
        </script>

        <div id="delayedReceiptPopup" style="display:none">
            <div class="layui-form  layuimini-form">
                <div class="layui-form-item">
                    <label class="layui-form-label">延迟收货时间</label>
                    <div class="layui-input-block">
                        <select id="delayedReceiptDays" name="delayedReceiptDays">
                            <option value="0" selected>0</option>
                            <option value="1">1天</option>
                            <option value="2">2天</option>
                            <option value="3">3天</option>
                            <option value="4">4天</option>
                            <option value="5">5天</option>
                            <option value="6">6天</option>
                            <option value="7">7天</option>
                            <option value="8">8天</option>
                            <option value="9">9天</option>
                            <option value="10">10天</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="../../lib/common/common.js" charset="utf-8"></script>
<script>
    let existLogistics = true;
    let countdownMap = new Map;
    layui.use(['form', 'table'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;

        table.render({
            elem: '#currentTableId',
            url: '/express/query/page/list',
            where: {
                // 默认是查业务状态为0的物流 和 没有物流信息物流排除
                logisticsModule: "GROUPBUY",
                existLogistics: true,
            },
            method: 'GET',
            contentType: 'application/x-www-form-urlencoded',
            resizable: false,// 禁用拖拽
            parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                };
            },
            toolbar: false,
            cols: [[
                {type: "checkbox"},
                {
                    field: 'numbering', title: '序号', width: 60, align: 'center', templet: function (d) {
                        return d.LAY_INDEX; //返回序号
                    }
                },
                {field: 'orderInfo', title: '订单信息', align: 'center', templet: '#orderInfoTemp'},
                {
                    field: 'deliveryTime',
                    title: '交易/发货时间',
                    sort: true,
                    align: 'center',
                    templet: '#deliveryTimeTemp',
                    width: 200,
                },
                {field: 'address', title: '收货信息', align: 'center', templet: '#addressTemp'},
                {field: 'logisticsInfo', title: '物流动态', align: 'center', templet: '#logisticsInfoTemp'},
            ]],
            limits: [50, 100, 150, 200],
            limit: 50,
            page: true,
            request: {
                pageName: 'pageNum',
                limitName: 'pageSize'
            },
            response: { //定义后端 json 格式，详细参见官方文档
                statusName: 'code', //状态字段名称
                statusCode: '200', //状态字段成功值
                msgName: 'msg', //消息字段
                countName: 'count', //总数字段
                dataName: 'data' //数据字段
            },
            done: function (res, curr, count) {
                // 计算倒计时
                clearTiming();
                let now = new Date();
                for (let i = 0; i < res.data.length; i++) {
                    let data = res.data[i];
                    let deliveryTime = new Date(data.deliveryTime);
                    let num = Math.floor(parseFloat(data.delayedReceiptDays))
                    let diffTime = (deliveryTime.getTime() + (num + 10) * 24 * 60 * 60 * 1000) - now.getTime();
                    if (diffTime > 0 && data.businessStatus === '0') {
                        let countdownElem = document.getElementById("countdown_" + data.id);
                        countdownElem.innerHTML = '<div style="color: red">' + formatTime(diffTime) + "后自动收货" + '<div/>';
                        const timerId = setInterval(function () {
                            let countdownElem = document.getElementById("countdown_" + data.id);
                            let diffTime = (deliveryTime.getTime() + (num + 10) * 24 * 60 * 60 * 1000) - (new Date()).getTime();
                            if (diffTime > 0) {
                                countdownElem.innerHTML = '<div style="color: red">' + formatTime(diffTime) + "后自动收货" + '<div/>';
                            } else {
                                countdownElem.innerHTML = '<div style="color: #00ba00">收货完成<div/>';
                            }
                        }, 1000);
                        countdownMap.set(data.id, timerId)
                    } else {
                        let countdownElem = document.getElementById("countdown_" + data.id);
                        countdownElem.innerHTML = '<div style="color: #00ba00">收货完成<div/>';
                    }
                }
            }
        });

        // 统计数据
        logisticsStatusStatistics();


        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            let checkStatus = table.checkStatus('currentTableId')
                , data = checkStatus.data;
            if (data.length === 1) {
                // 修改按钮启用
                $(".single-select—btn").removeClass('layui-btn-disabled')
            } else {
                $(".single-select—btn").addClass('layui-btn-disabled')
            }
        });


        $('.delayedReceipt').click(function () {
            let checkStatus = table.checkStatus('currentTableId')
                , data = checkStatus.data;
            if (data.length === 0) {
                layer.alert('至少选中一行数据');
                return;
            }
            if (data[0].businessStatus === '1') {
                layer.alert('订单已完成，不可设置');
                return;
            }
            $.ajax({
                type: "get",
                url: '/buying/get/' + data[0].moduleId,
                dataType: 'json',
                contentType: 'application/x-www-form-urlencoded',
                success: function (req) {
                    let reqData = req.data;
                    layui.use(['form'], function () {
                        let form = layui.form,
                            $ = layui.$;
                        $("#delayedReceiptDays").val(reqData.delayedReceiptDays)
                        // 新增
                        const index = layer.open({
                            title: '延迟收货时间',
                            type: 1,
                            btn: ['确定', '取消'],
                            content: $('#delayedReceiptPopup'),
                            area: ['30%', '260px'],
                            success: function (layero, index) {

                            },
                            yes: function (index, layero) {
                                let days = $("#delayedReceiptDays").val()
                                if (!isNotNull(days)) {
                                    layer.alert('请先选择延迟收货时间');
                                    return;
                                }
                                $.ajax({
                                    type: "post",
                                    url: '/trade/order/delayed/receipt/' + reqData.id + '/' + days,
                                    dataType: 'json',
                                    contentType: 'application/json; charset=UTF-8',
                                    success: function (req) {
                                        if (req.code === '200') {
                                            layer.msg('设置成功');
                                            layer.close(index);
                                            // 关闭弹出层
                                            reloadTable();
                                        } else {
                                            layer.msg(req.msg);
                                        }

                                    },
                                    error: function (e) {
                                        layer.msg(e.msg);
                                    }
                                })
                            },
                        });
                    })
                },
                error: function (e) {
                    layer.msg("数据有误");
                }
            })
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            // 默认查询全部
            data.field.logisticsModule = "GROUPBUY";
            table.reload('currentTableId', {
                page: {
                    curr: 1
                }
                , where: data.field
            }, 'data');
            logisticsStatusStatistics();
            return false;
        });


        form.on('checkbox(showAll)', function (data) {
            let formDate = form.val('searchForm');
            if (data.elem.checked) {
                existLogistics = false;
            } else {
                existLogistics = true;
            }
            formDate.logisticsModule = "GROUPBUY";
            formDate.existLogistics = existLogistics;
            table.reload('currentTableId', {
                page: {
                    curr: 1
                }
                , where: formDate
            }, 'data');
            logisticsStatusStatistics();
        });


    });

    /**
     * 重载表格数据
     */
    function reloadTable() {
        layui.use(['table'], function () {
            let table = layui.table;
            table.reload('currentTableId', {
                url: '/express/query/page/list'
            });
        })
    }

    function clearTiming() {
        // 清除掉所有的定时器
        countdownMap.forEach((value, key) => {
            clearInterval(value)
        })
        countdownMap = new Map;
    }

    function stateSearch(state) {
        layui.use(['form', 'table', 'laydate', 'colorpicker'], function () {
            var $ = layui.jquery,
                form = layui.form,
                table = layui.table;
            let formDate = form.val('searchForm');
            if (state === 'IN_TRANSIT') {
                formDate.inTransit = true;
            }
            if (state === 'SIGN') {
                formDate.status = 3;
            }
            if (state === 'FORTYEIGHT_HOUR_RECEIVING_DATA') {
                formDate.fortyEighthourData = true;
            }
            if (state === 'BUSINESS_COMPLETED') {
                formDate.businessStatus = 1;
            }
            formDate.logisticsModule = "GROUPBUY";
            formDate.existLogistics = existLogistics;
            table.reload('currentTableId', {
                page: {
                    curr: 1
                }
                , where: formDate
            }, 'data');
        });
    }

    function toOrderDetail(id) {
        if (!isNotNull(id)) {
            layer.msg("数据异常，请重试");
            return;
        }
        layui.use(['table'], function () {
            let table = layui.table;
            var index = layer.open({
                title: '订单详情',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: ['100%', '100%'],
                content: '../orders/order-detail.html?recordId=' + id,
                end: function () {
                    //关闭弹框后触发
                    reloadTable()
                }
            });
            $(window).on("resize", function () {
                layer.full(index);
            });
        })

    }

    function toLogisticsSpreadDetail(id) {
        if (!isNotNull(id)) {
            layer.msg("数据异常，请重试");
            return;
        }
        layui.use(['table'], function () {
            let table = layui.table;
            var index = layer.open({
                title: '物流详情',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: ['40%', '80%'],
                content: './logisticsSpreadDetail.html?id=' + id,
                end: function () {

                }
            });
        })

    }

    function formatTime(diffTime) {
        let days = Math.floor(diffTime / (24 * 60 * 60 * 1000));
        let hours = Math.floor((diffTime % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
        let minutes = Math.floor((diffTime % (60 * 60 * 1000)) / (60 * 1000));
        let seconds = Math.floor((diffTime % (60 * 1000)) / 1000);
        return days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";
    }

    function logisticsStatusStatistics() {
        layui.use(['form'], function () {
            var form = layui.form,
                $ = layui.$;
            let formDate = form.val('searchForm');
            formDate.logisticsModule = "GROUPBUY";
            formDate.existLogistics = existLogistics;
            $.ajax({
                type: "GET",
                url: '/express/query/status/statistics',
                data: formDate,
                contentType: 'application/x-www-form-urlencoded',
                dataType: 'json',
                success: function (req) {
                    if (req.code === '200') {
                        let data = req.data;
                        if (data) {
                            const myMap = new Map(Object.entries(data));
                            // 更新统计数据
                            myMap.forEach((value, key) => {
                                let id = '#' + key
                                $(id).text('(' + value + ')');
                            });
                        }
                    } else {
                        layer.msg(req.msg);
                    }
                },
                error: function (e) {
                    layer.msg(e.msg);
                }
            })
        });
    }
</script>

</body>
</html>